﻿using PivotData;
using PivotIO.XML;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace PivotWebsite.Controllers
{
    /// <summary>
    /// Get/set properties.
    /// </summary>
    public class CollectionPropertiesController : ApiController
    {
        /// <summary>
        /// Return a collection property value.
        /// </summary>
        /// <param name="cId">Collection ID</param>
        /// <param name="propName">Valid name of a property.</param>
        /// <returns>Property value, or the empty string if it isn't present.</returns>
        public string Get(int cId, string propName)
        {
            var cinfo = CollectionInfoIO.LoadCollection(cId);
            if (cinfo == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            CheckProperty(propName);

            var v = cinfo.Properties.Where(i => i.key == propName).Select(i => i.value).FirstOrDefault();
            if (v == null)
                return "";
            return v;
        }

        /// <summary>
        /// Only legal property names are allowed in here.
        /// </summary>
        /// <param name="propName"></param>
        private void CheckProperty(string propName)
        {
            if (propName != "Description"
                && propName != "PartitionByFacet")
                throw new HttpResponseException(HttpStatusCode.BadRequest);
        }

        /// <summary>
        /// Return 
        /// </summary>
        /// <param name="cID"></param>
        /// <param name="propName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public void Put(int cId, string propName, string value)
        {
            var cinfo = CollectionInfoIO.LoadCollection(cId);
            if (cinfo == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            CheckProperty(propName);
            var r = cinfo.Properties.Where(i => i.key != propName);
            cinfo.Properties = r.Concat(new CollectionInfo.PropInfo[] { new CollectionInfo.PropInfo(propName, value) }).ToArray();
            CollectionInfoIO.SaveCollection(cinfo);
        }
    }
}
